import { bind_patient_select, patient_guidance, patient_guidance_info } from '@/services/guide';
import { get_platformuser_select } from '@/services/patient';
import { ActionType, ProForm, ProFormSelect, ProFormTextArea } from '@ant-design/pro-components';
import { DatePicker, Divider, Form, message, Modal, Spin } from 'antd';
import dayjs from 'dayjs';
import moment from 'moment';
import { useEffect, useState } from 'react';

interface Iprops {
  isShowEditInhospital: (show: boolean) => void;
  isEditInhospital: boolean;
  actionRef: React.MutableRefObject<ActionType | undefined>;
  inHospitalId: number | undefined;
}
type TForm = {
  patient_id: number;
  platform_user_id: number;
  plan_time: string;
  remark: string;
};
const EditInhospital = (props: Iprops) => {
  const { isEditInhospital, isShowEditInhospital, actionRef, inHospitalId } = props;
  const [form] = Form.useForm();
  // 存储医生列表
  const [doctors, setDoctors] = useState([]);
  // 存储患者列表
  const [patientList, setPatientList] = useState([]);
  // 存储院内指导计划详情
  const [gudienceInfo, setGudienceInfo] = useState<TForm | undefined>(undefined);

  // 页面初始化
  useEffect(() => {
    // 获取指导计划详情
    const get_patient_guidance_info = async () => {
      if (inHospitalId) {
        let res: any = await patient_guidance_info({ id: inHospitalId });
        console.log('院内指导计划详情', res);
        if (res.msg == 'ok') {
          let parmas: any = await bind_patient_select({ id: res.data.platform_user_id });
          if (parmas.msg == 'ok') {
            console.log('pa', parmas);

            let list: any = [];
            parmas.data.map((item: any) => {
              let lemp: any = {};
              lemp.value = item.id;
              lemp.label = item.username;
              list.push(lemp);
            });
            setPatientList(list);
          }
          setGudienceInfo(res.data);
        }
      }
    };
    // 获取指导医生列表
    get_doctor_select();
    get_patient_guidance_info();
  }, []);

  // 获取指导医生列表
  const get_doctor_select = async () => {
    let res: any = await get_platformuser_select();
    console.log('医生列表', res);
    if (res.msg == 'ok') {
      let list: any = [];
      res.data.map((item: any) => {
        let lemp: any = {};
        lemp.value = item.id;
        lemp.label = item.username;
        list.push(lemp);
      });
      setDoctors(list);
    }
  };
  // 获取患者列表
  const get_patient_selevt = async (value: number) => {
    // 先清空患者列表
    form.setFieldsValue({ patient: null });
    console.log('医生id', value);
    let res: any = await bind_patient_select({ id: value });
    console.log('res', res.data);
    if (res.msg == 'ok') {
      let list: any = [];
      res.data.map((item: any) => {
        let lemp: any = {};
        lemp.value = item.id;
        lemp.label = item.username;
        list.push(lemp);
      });
      setPatientList(list);
    }
  };

  // 计划指导日期禁用 (只能选择当天或者当天之后的时间)
  const disabledDate = (current: any) => {
    return current && current < moment().subtract(1, 'day');
  };

  // 编辑院内指导计划
  const edit_patient_guidance = async (value: {
    doctor: number;
    patient: number;
    time: string;
    textarea: string;
  }) => {
    console.log('value', value);

    let request_body = {
      id: inHospitalId,
      platform_user_id: value.doctor,
      patient_id: value.patient,
      plan_time: value.time,
      remark: value.textarea ? value.textarea : '',
    };
    let res: any = await patient_guidance(request_body);
    console.log('编辑院内指导', res);
    if (res.msg == 'ok') {
      actionRef.current?.reload();
      message.success('编辑院内指导计划成功！');
      isShowEditInhospital(false);
    } else {
      message.error(res.msg);
    }
  };
  return (
    <Modal
      title="编辑院内指导"
      centered
      open={isEditInhospital}
      onCancel={() => isShowEditInhospital(false)}
      width={500}
      footer={null}
    >
      <Divider />
      {gudienceInfo === undefined ? (
        <div
          style={{
            margin: '20px 0',
            marginBottom: '20px',
            padding: '30px 50px',
            textAlign: 'center',
          }}
        >
          <Spin size="large" />
        </div>
      ) : (
        <ProForm<{
          doctor: number;
          patient: number;
          time: string;
          textarea: string;
        }>
          form={form}
          layout="horizontal"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 15 }}
          onReset={() => isShowEditInhospital(false)}
          onFinish={(value) => edit_patient_guidance(value)}
          submitter={{
            // 配置按钮文本
            searchConfig: {
              resetText: '取消',
              submitText: '确定',
            },
            resetButtonProps: {
              style: {
                display: 'block',
                position: 'absolute',
                left: 'calc(50% - 107px)',
              },
            },
            submitButtonProps: {
              style: {
                display: 'block',
                position: 'absolute',
                right: 'calc(50% - 107px)',
              },
            },
          }}
        >
          <ProFormSelect
            name="doctor"
            label="指导医生"
            options={doctors}
            placeholder="请选择指导医生"
            rules={[{ required: true, message: '请选择指导医生' }]}
            onChange={(value: number) => get_patient_selevt(value)}
            initialValue={gudienceInfo.platform_user_id}
            disabled
          />
          <ProFormSelect
            name="patient"
            label="患者"
            options={patientList}
            placeholder="请选择患者"
            rules={[{ required: true, message: '请选择患者' }]}
            initialValue={gudienceInfo.patient_id}
            disabled
          />
          <Form.Item
            name="time"
            label="指导时间"
            rules={[
              {
                required: true,
                message: '请选择指导时间',
              },
            ]}
            initialValue={dayjs(gudienceInfo.plan_time, 'YYYY-MM-DD')}
          >
            <DatePicker disabledDate={disabledDate} style={{ width: '282px' }} />
          </Form.Item>

          <ProFormTextArea
            name="textarea"
            label="备注"
            placeholder=""
            initialValue={gudienceInfo.remark}
            rules={[
              {
                max: 100,
                message: '允许输入字符最大数为100',
              },
            ]}
          />
          <br />
        </ProForm>
      )}

      <br />
    </Modal>
  );
};
export default EditInhospital;
